package com.example.essayController;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.example.essayRes.User;

public class UserController extends Controller{
	private DocumentBuilderFactory dbFactory;   
	private DocumentBuilder builder;
	//private HttpClient httpClient;
	
	public UserController(){}
	
	public boolean init() {
		dbFactory = DocumentBuilderFactory.newInstance();  
		try {
			builder = dbFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
	
	public User getUser(String userName, String password) throws SAXException, IOException{
		Document document = builder.parse(siteUri + projectName + "user/?name="+ userName+"&password=" + password);
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("user");
		if (nodeList.getLength() > 0) {
			NodeList recNode = nodeList.item(0).getChildNodes();
			if (recNode.getLength() > 0) {
				String ID = null, type = null;
				NodeList attrNode = recNode.item(0).getChildNodes();
				for (int i = 0; i < attrNode.getLength(); i++)
					if ("type".equals(attrNode.item(i).getNodeName())) {
						type = attrNode.item(i).getFirstChild().getNodeValue();
					}
					else if ("primarykey".equals(attrNode.item(i).getNodeName())) {
						ID = attrNode.item(i).getFirstChild().getNodeValue();
					}
				return new User(ID, userName, password, type);	
			}
		}
		return null;
	}
	
	private boolean findUser(User user) throws SAXException, IOException{
		Document document = builder.parse(siteUri + projectName + "user/?name="+ user.getName()+"&password=" + user.getPassword());
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("user");
		return (nodeList.getLength() > 0);
	}
	
	private boolean findUserByName(User user) throws SAXException, IOException{
		Document document = builder.parse(siteUri + projectName + "user/?name="+ user.getName());
		Element root = document.getDocumentElement();
		NodeList nodeList = root.getElementsByTagName("user");
		return (nodeList.getLength() > 0);
	}
	
	private boolean deleteUser(User user) throws ClientProtocolException, IOException, SAXException {
		// TODO Need to delete all essays of this user
		if (!findUser(user)) return false;
		execHttpDelete(siteUri + projectName + "user/" + user.getID());
		return true;
	}
	
	public boolean addUser(User user) throws TransformerException, ClientProtocolException, IOException, SAXException {
		// Could be more Strong, like checking response.getStatusLine()
		if (findUserByName(user)) return false;
		
		// createUser don't have ID
		String userID = user.getName();
		
		Document document = builder.newDocument();
		Element xmlUser = document.createElement("user"),
				pKey = document.createElement("primaryKey"),
				name = document.createElement("name"),
				password = document.createElement("password"),
				type = document.createElement("type"),
				record = document.createElement("record");
		xmlUser.setAttribute("uri", projectName + "user/"+userID);
		xmlUser.setAttribute("description", "user");
		pKey.setTextContent(userID);
		name.setTextContent(user.getName());
		password.setTextContent(user.getPassword());
		type.setTextContent(user.getType());
		//Do not setAttribute, becuase I think it's not neccessary when we use RMP tool.
		//pKey.setAttribute("attributeName", "name");
		//pKey.setAttribute("type", "String");
		//name.setAttribute("attributeName", "name");
		//name.setAttribute("type", "String");
		//password.setAttribute("attributeName", "name");
		//password.setAttribute("type", "String");
		record.appendChild(pKey);
		record.appendChild(name);
		record.appendChild(password);
		record.appendChild(type);
		xmlUser.appendChild(record);
		document.appendChild(xmlUser);
		
		execHttpPost(document);
		return true;
	}
}
